<?php

/**
 * This is the model class for table "{{mem_group}}".
 *
 * The followings are the available columns in table '{{mem_group}}':
 * @property integer $zmg_id
 * @property string $zmg_title
 * @property string $name
 * @property integer $type
 * @property string $description
 * @property string $bizrule
 * @property string $data
 * @property integer $zmt_id
 */
class MemGroup extends CActiveRecord
{

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return MemGroup the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{mem_group}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('zmg_title', 'required','on'=>'editgroup'),
			array('type, zmt_id', 'numerical', 'integerOnly'=>true),
			array('name', 'length', 'max'=>100),
			array('zmg_title', 'length','min'=>4, 'max'=>50,'on'=>'editgroup'),
			array('description', 'length', 'max'=>255),
			array('bizrule, data', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('zmg_id, zmg_title, name, type, description, bizrule, data, zmt_id', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
				'childs'=>array(self::HAS_MANY, 'MemPrivilege', array('parent'=>'name')),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'zmg_id' => 'ID',
			'zmg_title' => '标题',
			'name' => "权限名称", 
			'type' => '类型',
			'description' => '描述',
			'bizrule' => '权限规则',
			'data' => '数据',
			'zmt_id' => '等级',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('zmg_id',$this->zmg_id);
		$criteria->compare('zmg_title',$this->zmg_title,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('type','1');
		$criteria->compare('description',$this->description,true);
		$criteria->compare('bizrule',$this->bizrule,true);
		$criteria->compare('data',$this->data,true);
		$criteria->compare('zmt_id',$this->zmt_id);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>'30',
			),
		));
	}
	//获取类型
	public function getType($type=null){
		if($type==null){
			return array(
				'1'=>'会员组',
				'2'=>'权限集',
				'3'=>'操作',
			);
		}else{
			$level = $this->getType();
			return $level[$type];
		}
	}

	/*
	 * 获取权限集列表
	 * */
	public function getPrivilege($type=null){
		if($type==null){
			$criteria=new CDbCriteria;
			$criteria->compare('type','2');
			$data = $this->findAll($criteria);
			return CHtml::listData($data,'name','zmg_title');
		}else{
			$level = $this->getPrivilege();
			if(array_key_exists($type,$level)){
				return $level[$type];
			}
		}
	}
	
	/*
	 * 获取商家中心操作集
	* */
	public function getCmpTask($type=null){
		if($type==null){
			$criteria=new CDbCriteria;
			$criteria->compare('type','2');
			$criteria->compare('name','company-',true);
			$data = $this->findAll($criteria);
			return CHtml::listData($data,'name','zmg_title');
		}else{
			$level = $this->getPrivilege();
			if(array_key_exists($type,$level)){
				return $level[$type];
			}
		}
	}
	
	/*
	 * 获取会员中心操作集
	* */
	public function getMemTask($type=null){
		if($type==null){
			$criteria=new CDbCriteria;
			$criteria->compare('type','2');
			$criteria->compare('name','member-',true);
			$data = $this->findAll($criteria);
			return CHtml::listData($data,'name','zmg_title');
		}else{
			$level = $this->getPrivilege();
			if(array_key_exists($type,$level)){
				return $level[$type];
			}
		}
	}
	
	/*
	 * 获取商家角色的权限操作
	 * */
	public function getCmpRoleAction($role){
		$criteria=new CDbCriteria;
		$criteria->compare('parent','cmp-'.$role);
		$model = MemPrivilege::model()->findAll($criteria);
		//$taskAction = CHtml::listData($model,'childs.child','childs.action.zmg_title');
		if(empty($model)){
			$taskAction = array();
		}else{
			foreach($model as $val){
				$taskAction[] = $val->child;
			}
		}
		//print_r($taskAction);
		return $taskAction;
	}
	
	/*
	 * 获取指定权限集的所有操作
	* */
	public function getTaskAction($task){
		$criteria=new CDbCriteria;
		$criteria->compare('name',$task);
		$model = MemGroup::model()->find($criteria);
		//$taskAction = CHtml::listData($model,'childs.child','childs.action.zmg_title');
		foreach($model->childs as $val){
			if(isset($val->action)){
				$taskAction[$val->child] = $val->action->zmg_title;
			}
		}
		if(empty($model->childs))
			$taskAction = array();
		//print_r($taskAction);
		return $taskAction;
	}
	
	/*
	 * 取会员组信息	 
	 */
   public function getMemGroup($type=null){
	   	if($type==null){
	   		$criteria=new CDbCriteria;
	   		$criteria->compare('type','1');
	   		$memGroup = MemGroup::model()->findAll($criteria);
	   		return CHtml::listData($memGroup,'zmg_id','zmg_title');
	   	}else{
	   		$level = $this->getMemGroup();
	   		if(array_key_exists($type,$level)){
	   			return $level[$type];
	   		}
	   	}
   }

   /*
	* 取指定会员组名称
	* @param int  $id 会员组ID  
    */
	
   public function getMemGroupName($id)
   {
   		//print_r($id);exit;
   		$MemGroupName = MemGroup::model()->findByAttributes(array('zmg_id'=>$id));

   		return $MemGroupName->zmg_title;
   }
   /*
    * 获取所有控制器
    * @param $modules array 模块名称用键名来标志eg:  array('member'=>'','company'=>'')
    */
   public function _getControllers($modules=null) {
   		$contPath = Yii::app()->getControllerPath();
   
   		$controllers = $this->_scanDir($contPath);
  		
	   	//如无指定模块，取得所有模块
	   	if($modules==null){
	   		$modules = Yii::app()->getModules();
	   	}else{
	   		$controllers = array();
	   	}

	   	$modControllers = array();
	   	foreach ($modules as $mod_id => $mod) {
	   		$moduleControllersPath = Yii::app()->getModule($mod_id)->controllerPath;
	   		$modControllers = $this->_scanDir($moduleControllersPath, $mod_id, "", $modControllers);
	   	}
	   	return array_merge($controllers, $modControllers);
   }
   /*
    *遍历文件获取文件夹下所有继承SBaseController的控制器
    * */
   private function _scanDir($contPath, $module="", $subdir="", $controllers = array()) {
   	$handle = opendir($contPath);
   	$del = '-';
   	while (($file = readdir($handle)) !== false) {
   		$filePath = $contPath . DIRECTORY_SEPARATOR . $file;
   		if (is_file($filePath)) {
   			if (preg_match("/^(.+)Controller.php$/", basename($file))) {
   			//	if ($this->_extendsSBaseController($filePath)) {
   					$controllers[] = (($module) ? $module . $del : "") .
   					(($subdir) ? $subdir . "." : "") .
   					str_replace(".php", "", $file);
   			//	}
   			}
   		} else if (is_dir($filePath) && $file != "." && $file != "..") {
   			$controllers = $this->_scanDir($filePath, $module, $file, $controllers);
   		}
   	}
   	return $controllers;
   }
   /*
    * 判断是否继承SBaseController
    * */
   private function _extendsSBaseController($controller) {
	   	$handle = file_get_contents($controller);
	   	if(strstr($handle,'SBaseController')){
	   		return true;
	   	}else{
	   		return false;
	   	}
   }
   /*
    * 获取控制器的相关信息
    * @return $actions所有操作
    * */
   public function _getControllerInfo($controller, $getAll = false) {
	   	$del = '-';
	   	$actions = array();
	   	$allowed = array();
	   	$auth = Yii::app()->authManager;
	   
	   	//检测是否是模块下的控制器
	   	if (substr_count($controller,$del )) {
	   		$c = explode($del, $controller);
	   		$controller = $c[1];
	   		$module = $c[0] .$del;
	   		$contPath = Yii::app()->getModule($c[0])->getControllerPath();
	   		$control = $contPath . DIRECTORY_SEPARATOR . str_replace(".", DIRECTORY_SEPARATOR, $controller) . ".php";
	   	} else {
	   		$module = "";
	   		$contPath = Yii::app()->getControllerPath();
	   		$control = $contPath . DIRECTORY_SEPARATOR . str_replace(".", DIRECTORY_SEPARATOR, $controller) . ".php";
	   	}
	   
	   	$task = $module . str_replace("Controller", "", $controller);
	   
	   	$taskViewingExists = $auth->getAuthItem($task . "Viewing") !== null ? true : false;
	   	$taskAdministratingExists = $auth->getAuthItem($task . "Administrating") !== null ? true : false;
	   	$delete = Yii::app()->request->getParam('delete');
	   
	   	$h = file($control);
	   	for ($i = 0; $i < count($h); $i++) {
	   		$line = trim($h[$i]);
	   		if (preg_match("/^(.+)function( +)action*/", $line)) {
	   			$posAct = strpos(trim($line), "action");
	   			$posPar = strpos(trim($line), "(");
	   			$action = trim(substr(trim($line),$posAct, $posPar-$posAct));
	   			$patterns[0] = '/\s*/m';
	   			$patterns[1] = '#\((.*)\)#';
	   			$patterns[2] = '/\{/m';
	   			$replacements[2] = '';
	   			$replacements[1] = '';
	   			$replacements[0] = '';
	   			$action = preg_replace($patterns, $replacements, trim($action));
	   			$itemId = $module . ucfirst(strtolower(str_replace("Controller", "", $controller))) .
	   			ucfirst(strtolower(preg_replace("/action/", "", $action,1)));
	   			if ($action != "actions") {
	   				$actions[$module . $action] = $itemId;
	   				if ($getAll) {
	   					if (in_array($itemId, $this->getAllowedAccess())) {
	   						$allowed[] = $itemId;
	   					}
	   				} else {
	   					if (in_array($itemId, $this->getAllowedAccess())) {
	   						$allowed[] = $itemId;
	   					} 
	   				}
	   			} else {
	   				//load controller
	   				if (!class_exists($controller, false)) {
	   					require($control);
	   				}
	   				$tmp = array();
	   				$controller_obj = new $controller($controller, $module);
	   				//Get actions
	   				$controller_actions = $controller_obj->actions();
	   				foreach ($controller_actions as $cAction => $value) {
	   					$itemId = $module . ucfirst(strtolower(str_replace("Controller", "", $controller))) . ucfirst(strtolower($cAction));
	   					$actions[$cAction] = $itemId;
	   					if ($getAll) {
	   						if (in_array($itemId, $this->getAllowedAccess())) {
	   							$allowed[] = $itemId;
	   						}
	   					} else {
	   						if (in_array($itemId, $this->getAllowedAccess())) {
	   							$allowed[] = $itemId;
	   						} 
	   					}
	   				}
	   			}
	   		}
	   	}
	   	return array($actions, $allowed, $delete, $task, $taskViewingExists, $taskAdministratingExists);
   }
   
   /*
    * 获取总是允许列表
    * */
   public function getAllowedAccess() {
	    $paramAllowed = array();
	    if(!is_file($this->getAlwaysAllowedFile())) {
		    $handle = fopen($this->getAlwaysAllowedFile(), "wb");
			fwrite($handle, "<?php\n return array();\n?>");
		    fclose($handle);
	    }
	    $guiAllowed = include($this->getAlwaysAllowedFile());
	    if(!is_array($guiAllowed)){
	    	$guiAllowed = array();
	    }
	    return $guiAllowed;
   }
   
   /*
    * 获取权限缓存文件
   * */
   public function getAlwaysAllowedFile() {
   		return Yii::getPathOfAlias(Yii::app()->params->alwaysAllowedPath).DIRECTORY_SEPARATOR."foregroup.php";
   }
   
   /*
    * 获取操作的备注名
    * */
   public function getActionName($type){
   	$criteria=new CDbCriteria;
   	
   	$criteria->compare('name',$type);
   	$action = $this->find($criteria);
   	if(!empty($action)){
   		return $action->zmg_title;
   	}else{
   		return NULL;
   	}
   }
   /*
    * 获取分配的权限集名
    * */
   public function getTasksName($type){
   		$type = trim($type);
		$criteria=new CDbCriteria;
		$criteria->compare('child',$type);
		$criteria->compare('zmv_type',1);
		$privilege = new MemPrivilege();
		$Tasks = $privilege->find($criteria);
		if(!empty($Tasks)){
	   		$model = $this->findByAttributes(array('name'=>$Tasks->parent));
	   		if(!empty($model)){
	   			return $model->attributes;
	   		}
		}
   }
   /*
    * 创建新的权限集名称
    * */
   public function createTaskName($controller){
   		//产生随机数
   		$hash = create_randomstr();
   		$name = trim($controller)."-".$hash;
   		$criteria=new CDbCriteria;
   		$criteria->compare('name',$name);
   		$criteria->compare('type','2');
   		if(!$this->exists($criteria)){
   			return $name;
   		}else{
   			$this->createTaskName($controller);
   		}
   }
   /*
    * 更新总是允许列表
    * @param $actions 数组  操作名称，格式：model-ControllerAction
    * @param $type 操作类型 1，添加 ; 2，减少
    * */
   public function updataAwayAllow($actions,$type=1){
	   	$paramAllowed = array();
	   	if(!is_file($this->getAlwaysAllowedFile())) {
	   		$handle = fopen($this->getAlwaysAllowedFile(), "wb");
	   		fwrite($handle, "<?php\n return array();\n?>");
	   		fclose($handle);
	   	}
	   	$guiAllowed = include($this->getAlwaysAllowedFile());
	   	if(!is_array($guiAllowed)){
	   		$guiAllowed = array();
	   	}
	   	if($type=='1'){
	   		$allowActions = array_merge($guiAllowed, $actions);
	   		$allowActions = array_unique($allowActions);
	   	}elseif($type=='2'){
	   		$allowActions =array_diff($guiAllowed,$actions);
	   	}
	   	$handle = fopen($this->getAlwaysAllowedFile(), "wb");
	   	fwrite($handle,"<?php \n return array(\n\t'" . implode("',\n\t'", $allowActions) . "'\n);\n?>");
	   	fclose($handle);
   }
   

}